<template>
    <div class="discussion-container">
       <!-- 我的收藏按钮 -->
       <div class="favorites-button-container">
        <button @click="viewFavorites" class="favorites-button">
          我的收藏
        </button>
      </div>
      <h1 class="discussion-title">讨论区</h1>
      <p class="course-name">课程名称：{{ course.name }}</p>
  
      <div class="search-container">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索帖子和评论..."
          class="search-input"
        />
        <button @click="searchDiscussions" class="search-button">搜索</button>
      </div>
      <div class="discussions">
    <div
      v-for="discussion in discussions"
      :key="discussion.id"
      class="discussion-item"
      @click="viewDiscussionDetail(discussion.id)"
    >
      <h4 class="discussion-header">
        {{ discussion.userName }} @ {{ discussion.date }}
      </h4>
      <p class="discussion-content">{{ discussion.content }}</p>
      <img v-if="discussion.image" :src="discussion.image" alt="讨论图片" class="discussion-image" />
      <div class="button-container">
        <button
          @click.stop="toggleLike(discussion)"
          :class="['like-button', { liked: discussion.liked }]"
        >
          {{ discussion.liked ? '取消点赞' : '点赞' }}
        </button>
  
        <button
        @click.stop="toggleFavorite(discussion)"
        :class="['favorite-button', { favorited: discussion.favorited }]"
      >
        {{ discussion.favorited ? '取消收藏' : '收藏' }}
      </button>

      <!-- 删除按钮 -->
      <button
        @click.stop="deleteDiscussion(discussion)"
        class="delete-button"
      >
        删除
      </button>
    </div>
  </div>
</div>
  
  
      <div class="comment-section">
        <h2>发布帖子</h2>
        <!-- 标题输入框 -->
        <input
          type="text"
          v-model="newDiscussion.title"
          placeholder="输入帖子的标题..."
          class="discussion-title-input"
        />
        <textarea
          v-model="newDiscussion.content"
          placeholder="提出您的疑问或领悟..."
          class="discussion-textarea"
        ></textarea>
        <div class="input-container">
          <input
            type="file"
            @change="onImageChange"
            accept="image/*"
            class="file-input"
          />
          <button @click="submitDiscussion" class="submit-button">提交</button>
        </div>
      </div>
    </div>
  </template>
  
  
  <script>
  import axios from 'axios';
  import { post } from '../../common/ajax';
  
  export default {
    data() {
      return {
        studentId: null,
        courseId: null,
        course: {}, // 存放课程信息
        discussions: [], // 存放讨论内容的数组
        newDiscussion: {
          title: "",
          content: "",
          image: null
        },
        searchQuery: "" // 新增搜索查询的状态
      };
    },
    created() {
      this.$store.commit('initializeState');  // 初始化 Vuex 状态
      this.studentId = this.$store.state.status.userId;
      this.courseId = this.$route.params.courseId; // 获取路由中的 courseId
      this.fetchCourseInfo(); // 获取课程信息
      this.fetchDiscussions(); // 获取讨论内容
    },
    methods: {
        async deleteDiscussion(discussion) {
  const confirmation = confirm("确定要删除这个帖子吗？");
  if (!confirmation) return;

  try {
    // 调用后端接口删除帖子
    const response = await axios.delete(`http://localhost:8085/posts/delete/${discussion.postId}`);

    if (response.status === 200) {
      // 删除成功，重新加载帖子
      alert("帖子已删除！");
      this.fetchDiscussions(); // 删除后重新获取讨论列表
    } else {
      alert("删除失败，请稍后再试！");
    }
  } catch (error) {
    console.error("删除帖子失败:", error);
    alert("删除帖子失败，请稍后再试！");
  }
},


      // 提交新帖子
      async submitDiscussion() {
        if (!this.newDiscussion.title || !this.newDiscussion.content) {
          alert("标题和讨论内容不能为空!");
          return;
        }
  
        const newPost = {
          courseId: this.courseId,
          title: this.newDiscussion.title,
          content: this.newDiscussion.content,
          imageUrl: this.newDiscussion.image || "",
          studentId: this.studentId
        };
        
  
        try {
          const response = await axios.post('http://localhost:8085/posts/create', newPost);
          const post = response.data;
          this.discussions.push({
            id: post.postId,
            user: post.userId,
            title: post.title,
            content: post.content,
            image: post.image,
            date: new Date().toLocaleString(),
            liked: false, // 新增的“喜欢”状态
            favorited: false // 新增的“收藏”状态
          });
  
          // 重置新帖内容
          this.newDiscussion.title = "";
          this.newDiscussion.content = "";
          this.newDiscussion.image = null;
        } catch (error) {
          console.error("创建帖子失败:", error);
          alert("提交失败，请稍后再试！");
        }
      },
  
      // 获取课程信息
      async fetchCourseInfo() {
        // API 调用获取课程信息
      },
  
      // 获取讨论内容
  async fetchDiscussions() {
    try {
      const response = await axios.get(`http://localhost:8085/posts/postsWithLikes`, {
        params: {
          courseId: this.courseId,
          userId: this.studentId
        }
      });
      console.log(response.data);  // 打印返回的数据，检查是否有 userName
  
      // 映射讨论数据
      this.discussions = response.data.map(discussion => ({
        ...discussion,
        postId: discussion.post_id,  // 将返回的 post_id 映射为 postId
        liked: discussion.isLiked === 1,  // 映射 isLiked 为 true 或 false
        favorited: discussion.isFavorited === 1,  // 映射 isFavorited 为 true 或 false
        likeCount: discussion.likeCount || 0,  // 初始化点赞数
        userName: discussion.userName || '匿名'  // 显示发帖人名字，默认显示为“匿名”
      }));
    } catch (error) {
      console.error("获取帖子失败:", error);
      this.discussions = [];
    }
  },
  
  
  
      // 图片上传处理
      onImageChange(event) {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = e => {
            this.newDiscussion.image = e.target.result;
          };
          reader.readAsDataURL(file);
        }
      },
  
      async searchDiscussions() {
    try {
      const response = await axios.get(
        `http://localhost:8085/posts/search?keyword=${this.searchQuery}&courseId=${this.courseId}`
      );
      this.discussions = response.data;
    } catch (error) {
      console.error("搜索帖子失败:", error);
      alert("搜索失败，请稍后再试！");
    }
  },
  
  
  
      // 查看帖子详细内容
      viewDiscussionDetail(discussionId) {
        this.$router.push({ name: "DiscussionDetail", params: { discussionId } });
      },
  
      async toggleLike(discussion) {
    try {
      console.log("当前讨论对象:", discussion);  // 查看discussion对象
      console.log("当前讨论的postId:", discussion.postId);  // 确认postId是否正确
  
      const data = new URLSearchParams({
        userId: this.studentId,
        postId: discussion.postId  // 使用映射后的字段 postId
      });
  
      if (discussion.liked) {
        // 取消点赞
        console.log("发送取消点赞请求的数据:", data.toString());
        await axios.post(`http://localhost:8085/posts/unlike`, data);
        discussion.liked = false;  // 更新状态
      } else {
        // 点赞
        console.log("发送点赞请求的数据:", data.toString());
        await axios.post(`http://localhost:8085/posts/like`, data);
        discussion.liked = true;  // 更新状态
      }
    } catch (error) {
      console.error("点赞/取消点赞失败:", error);
      alert("操作失败，请稍后再试！");
    }
  },
  
  
  
  
  
  
  
  async toggleFavorite(discussion) {
    try {
      // 检查 studentId 是否正确
      console.log("当前的 studentId:", this.studentId); // 输出当前 studentId，确保它不是 -1
  
      const params = new URLSearchParams();
      params.append("userId", this.studentId);
      params.append("postId", discussion.postId);
  
      // 根据当前是否已收藏来发送请求
      if (discussion.favorited) {
        // 如果已收藏，则取消收藏
        console.log("发送取消收藏请求的数据:", { userId: this.studentId, postId: discussion.postId }); // 打印请求数据
        await axios.post('http://localhost:8085/posts/unfavorite', params);  // 发送 POST 请求
        discussion.favorited = false;
      } else {
        // 如果未收藏，则收藏
        console.log("发送收藏请求的数据:", { userId: this.studentId, postId: discussion.postId }); // 打印请求数据
        await axios.post('http://localhost:8085/posts/favorite', params);  // 发送 POST 请求
        discussion.favorited = true;
      }
    } catch (error) {
      console.error("收藏/取消收藏失败:", error);
      alert("操作失败，请稍后再试！");
    }
  }
  ,
  
  async viewFavorites() {
    try {
      // 调用后端接口获取用户收藏的帖子
      const response = await axios.get('http://localhost:8085/posts/favorites', {
        params: {
          userId: this.studentId
        }
      });
  
      // 处理返回的数据，确保正确映射点赞和收藏的状态
      this.discussions = response.data.map(post => ({
        postId: post.postId,
        title: post.title,
        content: post.content,
        image: post.image,
        likeCount: post.likeCount || 0,
        date: new Date(post.date).toLocaleString(),
        liked: post.isLiked === 1,  // 映射点赞状态
        favorited: true,  // 收藏状态应该始终为true，因为我们在收藏列表
      }));
    } catch (error) {
      console.error('获取收藏失败:', error);
      alert('获取收藏失败，请稍后再试！');
    }
  }
  
  
    }
    };
  </script>
  
  
  
<style scoped>
  /* 新增按钮样式 */
  /* 我的收藏按钮样式 */
  .favorites-button-container {
    position: absolute;
    top: 20px;  /* 距离页面顶部 */
    left: 20px; /* 距离页面左边 */
    z-index: 100; /* 确保按钮在其他元素上方 */
  }
  /* 删除按钮样式 */
.delete-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  background-color: #dc3545; /* 使用红色表示删除 */
  color: white;
  transition: background-color 0.3s, opacity 0.3s;
}

/* 删除按钮悬停效果 */
.delete-button:hover {
  background-color: #c82333; /* 深红色表示删除 */
  opacity: 0.8;
}

/* 删除按钮与点赞、收藏按钮保持一致 */
.like-button,
.favorite-button,
.delete-button {
  display: inline-block;
  margin-right: 10px; /* 保证按钮之间有适当间距 */
}
  .like-button,
  .favorite-button {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  .favorites-button {
    background-color: #f8f9fa;
    border: 1px solid #007bff;
    color: #007bff;
    font-size: 16px;
    padding: 8px 16px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s, color 0.3s;
  }
  
  .favorites-button:hover {
    background-color: #007bff;
    color: white;
  }
  
  .like-button {
    background-color: #007bff;
    color: white;
  }
  
  .favorite-button {
    background-color: #28a745;
    color: white;
  }
  
  .like-button.liked {
    background-color: #ffc107; /* 黄色表示已喜欢 */
  }
  
  .favorite-button.favorited {
    background-color: #dc3545; /* 红色表示已收藏 */
  }
  
  .like-button:hover,
  .favorite-button:hover {
    opacity: 0.8;
  }
  
  /* 容器和讨论项样式 */
  .discussion-item {
    background-color: #fff;
    border: 1px solid #e1e1e1;
    border-radius: 5px;
    padding: 15px;
    margin-bottom: 15px;
    transition: box-shadow 0.3s;
  }
  
  .discussion-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  /* 新增样式：标题输入框 */
  .discussion-title-input {
    width: 100%;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
  }
  
  .discussion-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
  
  .discussion-title {
    text-align: center;
    color: #333;
  }
  
  .course-name {
    text-align: center;
    color: #666;
    margin-bottom: 20px;
  }
  
  .search-container {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .search-input {
    width: 70%;
    padding: 10px;
    border: 1px solid #007bff;
    border-radius: 5px 0 0 5px;
    outline: none;
    font-size: 14px;
  }
  
  .search-button {
    padding: 10px 15px;
    border: none;
    border-radius: 0 5px 5px 0;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  .search-button:hover {
    background-color: #0056b3;
  }
  
  .discussions {
    margin-bottom: 20px;
  }
  
  .discussion-item {
    background-color: #fff;
    border: 1px solid #e1e1e1;
    border-radius: 5px;
    padding: 15px;
    margin-bottom: 15px;
    transition: box-shadow 0.3s;
  }
  
  .discussion-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .discussion-header {
    margin: 0 0 10px;
    font-size: 1.1em;
    color: #007bff;
  }
  
  .discussion-content {
    margin: 0 0 10px;
    line-height: 1.5;
  }
  
  .discussion-image {
    max-width: 100%;
    height: auto;
    margin-top: 10px;
    border-radius: 5px;
  }
  
  .comment-section {
    margin-top: 30px;
    padding: 15px;
    background-color: #fff;
    border: 1px solid #e1e1e1;
    border-radius: 5px;
  }
  
  .input-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }
  
  .discussion-textarea {
    width: 100%;
    height: 100px;
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    resize: none;
    font-size: 14px;
  }
  
  .file-input {
    margin-bottom: 10px;
    font-size: 14px;
    padding: 10px;
    border: 1px solid #0b7ffb;
    border-radius: 5px;
    background-color: rgba(244, 245, 249, 0.719)
    }
  </style>